package cn.kgc.service.impl;

import cn.kgc.client.RestDmImageClient;
import cn.kgc.client.RestDmUserClient;
import cn.kgc.config.WxConfig;
import cn.kgc.dto.Dto;
import cn.kgc.dto.DtoUtil;
import cn.kgc.pojo.DmImage;
import cn.kgc.pojo.DmUser;
import cn.kgc.service.UserService;
import cn.kgc.service.WxService;
import cn.kgc.utils.Constants;
import cn.kgc.utils.HttpclientUtils;
import cn.kgc.utils.UrlUtils;
import cn.kgc.vo.DmUserVo;
import cn.kgc.vo.TokenVo;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class WxServiceImpl implements WxService {

    @Resource
    WxConfig wxConfig;

    @Resource
    UserService userService;

    @Resource
    RestDmUserClient restDmUserClient;

    @Resource
    RestDmImageClient restDmImageClient;
    //微信登录
    @Override
    public Dto<Object[]> wxlogin(String code) throws Exception {

        // 1.根据code获取accessToken
        //https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
        Map accessTokenMap =  getAccessTokenInfo(code);
        // 2.accessToken获取用户的个人信息
        Map userInfoMap = getUserInfoByAccessToken(accessTokenMap);


        //实现自身的业务
        //3.用户去数据库中查询wxUserId有没有这个openid，直接远程服务调用，List对象---空的--->没有这个对象
        Map map  = new HashMap<>();
        map.put("wxUserId",userInfoMap.get("unionid"));
        List<DmUser> dmUserListByMap = restDmUserClient.getDmUserListByMap(map);

        //4.如果没有则插入一条这个用户dm_user的数据到数据库（实现一个注册的效果），将用户的头像信息放入dm_base中
        if (CollectionUtils.isEmpty(dmUserListByMap)||dmUserListByMap.size()==0) {
            //如果为空就创建一个
            DmUser dmUser = new DmUser();
            //set微信用户id
            dmUser.setWxUserId((String) userInfoMap.get("unionid"));
            //set微信用户昵称
            dmUser.setNickName((String) userInfoMap.get("nickname"));
            //set微信用户性别
            dmUser.setSex((Integer) userInfoMap.get("sex"));
        //添加用户
            Integer addDmUser = restDmUserClient.qdtxAddDmUser(dmUser);
            if (addDmUser>0){
                //获取用户
                DmUser user = (DmUser) restDmUserClient.getDmUserListByMap(map).get(0);
                //创建image对象
                DmImage dmImage = new DmImage();
                dmImage.setType(Constants.Image.ImageType.normal);
                dmImage.setType(Constants.Image.ImageCategory.user);
                Integer userId = user.getId().intValue();
                //设置关联id
                dmImage.setTargetId(userId);
                dmImage.setImgUrl((String) userInfoMap.get("headimgurl"));

                Integer image = restDmImageClient.qdtxAddDmImage(dmImage);
                if (image>0) {

                    log.info("添加用户头像成功");
                } else {
                    log.info("添加用户头像失败");
                }
                log.info(Constants.DATABASE_OPERATION_SUCCEED);
            }else{
                log.info("添加用户失败");
            }
        }

        //查询为了防止报空指针
        List<DmUser> dmUserListByMaps = restDmUserClient.getDmUserListByMap(map);
        DmUser dmUser = dmUserListByMaps.get(0);
        DmUserVo dmUserVo = new DmUserVo();

        //获取用户头像
        List<DmImage> dmImage_defaultImage = restDmImageClient.getDmImage_DefaultImage(dmUser.getId(),
                Constants.Image.ImageType.normal,
                Constants.Image.ImageCategory.user);
        dmUserVo.setImageId(dmImage_defaultImage.get(0).getId());
        dmUserVo.setImgUrl(dmImage_defaultImage.get(0).getImgUrl());

        //复制信息到dmuserVo中
        BeanUtils.copyProperties(dmUser,dmUserVo);
        dmUserVo.setUserId(dmUser.getId());

        //5.根据用户的openId生成我们系统的token
        String openidToken = userService.generateToken((String) userInfoMap.get("openid"));
        Date date = new Date();
        TokenVo tokenVo = new TokenVo();
        tokenVo.setToken(openidToken);
        tokenVo.setExpTime(date.getTime() + Constants.Redis_Expire.SESSION_TIMEOUT * 1000);
        //设置生成时间
        tokenVo.setGenTime(date.getTime());

        //6.将用户登录的信息放入redis中，并且还要把token放入redis中
        userService.saveToken(openidToken,dmUserVo);

        //7.返回我们系统生成的tokenVo+userVo(微信信息)
        return DtoUtil.returnDataSuccess( new Object[]{tokenVo,dmUserVo}) ;
    }


    //通过访问令牌获取用户信息
    private Map getUserInfoByAccessToken(Map accessTokenMap) {
        log.info("HttpResult--->Map:{}+map");

        //获取访问令牌
        String accessToken = (String) accessTokenMap.get("access_token");
        //获取openId
        String openId = (String) accessTokenMap.get("openid");
        StringBuffer userInfoUrl = new StringBuffer("https://api.weixin.qq.com/sns/userinfo?access_token=");
        userInfoUrl.append(accessToken);
        userInfoUrl.append("&openid=");
        userInfoUrl.append(openId);

        log.info("http请求获取微信用户信息参数"+userInfoUrl.toString());
        //发送请求
        String userinfo = HttpclientUtils.get(userInfoUrl.toString());

        log.info("Http请求微信获取用户信息结果====={}",userinfo);
        Map userinfoMap = JSON.parseObject(userinfo, Map.class);
        return userinfoMap;

    }


    //获取访问令牌信息
    @Nullable
    private Map getAccessTokenInfo(String code) {
        StringBuffer urlStrBuffer = new StringBuffer("https://api.weixin.qq.com/sns/oauth2/access_token?appid=");
        urlStrBuffer.append(wxConfig.getAppid());
        urlStrBuffer.append("&secret=");
        urlStrBuffer.append(wxConfig.getSecret());
        urlStrBuffer.append("&code=");
        urlStrBuffer.append(code);
        urlStrBuffer.append("&grant_type=authorization_code");

        //发送http请求？  client--->URLUTILS
        //String httpresult = HttpclientUtils.get(urlStringBuffer.toString());
        //  log.info("HttpclientUtils发送http请求到微信，获取accessToken:{}"+httpresult);

        String loadURL = UrlUtils.loadURL(urlStrBuffer.toString());
        log.info("UrlUtils发送http请求到微信，获取accessToken:{}",loadURL);
        //String json ---->java Map
        Map urlMap = JSON.parseObject(loadURL, Map.class);

        return urlMap;
    }
}
